package com.heima.article.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.article.service.ArticleFreemarkerSrevice;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class ArticleFreemarkerSreviceImpl implements ArticleFreemarkerSrevice {


    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 生成静态文件上传到minIO中
     * @param apArticle
     * @param content
     */

    @Override
    public String buildArticleToMinIo(ApArticle apArticle, String content) {
        //已知文章的id
        String path=null;
        Template template = null;
        //4.1 获取文章内容
        if(StringUtils.isNotBlank(content)){
            //4.2 文章内容通过freemarker生成html文件

            StringWriter out = new StringWriter();

            try {
                template = configuration.getTemplate("article.ftl");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

                //数据模型
                Map<String, Object> contentData = new HashMap<>();
                contentData.put("content", JSONArray.parseArray(content));

            try {
                //合成
                template.process(contentData, out);
            } catch (TemplateException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


            //4.3 把html文件上传到minio中
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);

            if (path != null) {
                return path;
            }

        }

        return path;
    }
}
